<?php
class RewriteRule
{

	/**
	 * Pattern constants for the replacement
	 *
	 * @var Strings
	 */
	const PATTERN_START = "{";
	const PATTERN_END   = "}";

	/**
	 * Contains rule data
	 * 
	 * @var ZeusLib_Object
	 */
	private static $data;
	
	/**
	 * Initializes data object
	 */
	public static function initialize()
	{
		// Initialize data variable
		self::$data = new ZeusLib_Object();
	}


	/**
	 * Adds a rule to the rule data
	 * ruleName: unique identifier
	 * ruleAssign: Array(url, match, param)
	 * 
	 * @param String $ruleName
	 * @param String[] $ruleAssign
	 */
	public static function add($ruleName, $ruleAssign)
	{
		// Check whether the required elements are given
		if(is_array($ruleAssign) && isset($ruleAssign['url'], $ruleAssign['match'], $ruleAssign['param']))
		{
			// Add the data
			self::$data->addData(array($ruleName => $ruleAssign));
		}
	}
	
	/**
	 * Get a url for the ruleName assigned with the ruleData
	 * Important: the order of ruleData is important
	 * 
	 * @param String $ruleName
	 * @param String $ruleData
	 */
	public static function get($ruleName, $ruleData)
	{
		// Get the rule assignments for the rule name
		$ruleAssign = self::$data->getData($ruleName);

		// Get the url
		$url = $ruleAssign['url'];

		// Iterate all assignments
		foreach($ruleAssign['param'] as $index => $key)
		{
			// Check whether the key is a number
			if(is_numeric($key))
			{
				// Replace index by data
				$url = str_replace(self::PATTERN_START.$index.self::PATTERN_END, $ruleData[$key], $url);
			}
		}

		// Return result
		echo $url;
	}
	
	/**
	 * Parses the given mod_rewrite_params get param to create required get values
	 */
	public static function parse()
	{
		// Get all assignments
		$ruleAssigns = self::$data->getData();

		// Iterate all
		foreach($ruleAssigns as $ruleAssign)
		{
			// Check whether mod_rewrite_params is given and the url match is okay
			if(isset($_GET['mod_rewrite_params']) && preg_match($ruleAssign['match'], $_GET['mod_rewrite_params'], $matches))
			{
				// Iterate all rule assigns
				foreach($ruleAssign['param'] as $index => $key)
				{
					// Check whether the key is numeric and we want to merge to a match
					if(is_numeric($key))
					{
						$_GET[$index] = $matches[$key+1];
					}
					// The key is not numeric and we want to define a static get param
					else
					{
						$_GET[$index] = $key;
					}
				}
			}
		}

		// Unset mod_rewrite_params get param to have clean get params
		unset($_GET['mod_rewrite_params']);
	}

}